/**
 * lib/checkit.shim
 *
 * @author xiaomi
 */

const lodash = require('lodash');
const Checkit = require('checkit');

// default lang
Checkit.language = 'zh';

// extend Checkit.i18n
Checkit.i18n.zh = lodash.defaultsDeep({
    messages: {
        unused: 'The {{label}}:{{var_0}} is already in use.',
        min: 'The {{label}} must be a number greater than or equal to {{var_1}}',
        max: 'The {{label}} must be a number less than or equal to {{var_1}}',
        json: 'The {{label}} must be a JSON.'
    }
}, Checkit.i18n.en);

// extend Checkit.Validator
lodash.assign(Checkit.Validator.prototype, {
    notBlank(val) {
        if(!lodash.trim(val)) {
            throw new Error('Blank value is not allow.');
        }
    },
    min(val, max) {
        return this.greaterThanEqualTo(val, max);
    },
    max(val, min) {
        return this.lessThanEqualTo(val, min);
    },
    json(val) {
        if(!val && typeof val !== 'string') {
            return false;
        }

        let obj;
        try {
            obj = JSON.parse(val);
        }
        catch(ex) { }

        if(!obj || typeof obj !== 'object') {
            return false;
        }
    }
});

// extend Checkit.Error
lodash.assign(Checkit.Error.prototype, {
    toString(flat) {
        return this.invokeMap('toString', flat).join('; ');
    }
});

module.exports = Checkit;
